<?php

namespace App\Http\Controllers\Admin;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;

use App\Models\Courses;
use App\Models\Organization;
use App\Models\Attachment;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class CourseController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        if(!$this->user->can('viewTeachesCourse')) abort(405);
        
        //if(!$this->user->can(array('viewEmploy','employ'))) abort(404);
        $title = $request->get('title');
        $orgname = $request->get('orgname');
        $query = Courses::with('organization');
        if(!empty($title))
            $query->where('name','like','%'.$title.'%');
        if(!empty($orgname))
        {
            $orgids = Organization::where('name','like','%'.$orgname.'%')->lists('id');
            $query->whereIn('org_id',$orgids);
        }
            
        $list = $query->orderBy('created_at','desc')->orderBy('id','desc')->paginate(20);

        return view('admin.course.index')->with('news', $list)->with('title', $title)->with('orgname',$orgname);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        if(!$this->user->can('editTeachesCourse')) abort(405);
        
        $organizations = Organization::all();
        return view('admin.course.add')->with('organization', $organizations);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        if(!$this->user->can('editTeachesCourse')) abort(405);
        
        /*验证表单*/
        $validator = Validator::make(
            ['name' => 'Course'],
            [
                'name' => 'required|max:255',
                /*'address' => 'required',
                'telphone' => 'required'*/
            ]
        );
        if ($validator->fails())
        {
            return redirect()->back()->withErrors($validator->errors());
        }
        //
        $course = new Courses;
        /*获取表单提交的数据并赋值给$course对象属性*/
        foreach (array_except(Input::all(), ['_token']) as $key => $val) {
            $course->$key = Input::get($key);
        }
        $org = Organization::find(Input::get('org_id',0));
        if(empty($org))
        {
            return Redirect::back()->withInput()->withErrors('机构信息错误,保存失败!');
        }
        $aid = Input::get('thumb', 0);
        DB::beginTransaction();
        try {
            $course->save();
            /*更新attchment记录*/
            $attch = Attachment::find($aid);
            if ($attch) {
                $attch->app_id = $course->id;
                $attch->save();
            }
            $org->incrementAdd('class_count',1);
            DB::commit();
        }catch (\PDOException $e){
            Log::info(['新增课程异常'=>$e->getMessage()]);
            DB::rollBack();
            return Redirect::back()->withInput()->withErrors('保存失败!');
        }
        return redirect("admin/teaches/organization/class");
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        if(!$this->user->can('viewTeachesCourse')) abort(405);

        $course = Courses::find($id);
        $organizations = Organization::all();
        $attachments = Attachment::where(['app_id' => $id, 'app' => 'course'])->get();
        return view('admin.course.edit')->with('course', $course)->with('org', $organizations)->with('attachment', $attachments);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function update(Request $request)
    {
        if(!$this->user->can('editTeachesCourse')) abort(405);
        
        /*验证表单*/
        $validator = Validator::make(
            ['name' => 'Course'],
            [
                'name' => 'required|max:255',
                /*'address' => 'required',
                'telphone' => 'required'*/
            ]
        );
        if ($validator->fails())
        {
            return redirect()->back()->withErrors($validator->errors());
        }
        $id = Input::get('id');
        $course = Courses::find($id);
        /*获取表单提交的数据并赋值给$course对象属性*/
        foreach (array_except(Input::all(), ['_token']) as $key => $val) {
            $course->$key = Input::get($key);
        }
        /*附件编号*/
        $aid = Input::get('thumb', 0);
        if ($course->save() ) {
            /*更新attchment记录*/
            $attch = Attachment::find($aid);

            if ($attch) {
                $attch->app_id = $id;
                $attch->save();
            }
            return redirect("admin/teaches/organization/class");

        } else {

            return Redirect::back()->withInput()->withErrors('保存失败!');
        }

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        if(!$this->user->can('deleteTeachesCourse')) 
            return $this->formatJson('error',$this->permerror);
        
        $course = Courses::find($id);
        $org = Organization::where('id','=',$course->org_id)->first();
        if ($course->delete()){
            if(!empty($org))
                $org->decrementDel('class_count',1);
            return  Response::json(array('status'=>'success','msg'=>'课程：［'.$course->name.'］ 删除成功'));
        }else{
            return  Response::json(array('status'=>'error','msg'=>'删除失败'));
        }
    }
}
